<template>
  <div id="SystemNotifyPage">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">消息筛选</span>
      </div>
      <div class="content-wrapper">
        <div class="search-item">
          <span class="item-label">消息级别</span>
          <el-select
            class="item-input"
            v-model="queryObj.priority"
            placeholder="请选择消息级别"
            clearable
            @change="searchHandle"
          >
            <el-option label="紧急" value="URGENT" />
            <el-option label="提醒" value="REMINDER" />
          </el-select>
        </div>
        <div class="search-item">
          <span class="item-label">消息状态</span>
          <el-select
            class="item-input"
            v-model="queryObj.status"
            placeholder="请选择消息状态"
            clearable
            @change="searchHandle"
          >
            <el-option label="已处理" value="PROCESSED" />
            <el-option label="未处理" value="UNPROCESSED" />
          </el-select>
        </div>
        <div class="search-btn" @click="searchHandle">筛选</div>
        <div v-if="userRole === 'admin'" class="add-btn" @click="addHandle">
          发布消息
        </div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">消息列表</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column
            prop="description"
            label="消息内容"
            min-width="130"
          />
          <el-table-column label="消息时间" min-width="150">
            <template #default="scope">
              {{ formatDate(scope.row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="消息级别" min-width="150">
            <template #default="scope">
              <div
                class="signal-status"
                :class="scope.row.priority === 'URGENT' ? 'abnormal' : 'normal'"
              >
                {{ scope.row.priority === "URGENT" ? "紧急" : "提醒" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="false" label="处理状态" min-width="150">
            <template #default="scope">
              <div
                class="signal-status"
                :class="
                  scope.row.status === 'PROCESSED' ? 'normal' : 'abnormal'
                "
              >
                {{ scope.row.status === "PROCESSED" ? "已处理" : "未处理" }}
              </div>
            </template>
          </el-table-column>
          <el-table-column v-if="false" label="处理意见" min-width="150">
            <template #default="scope">
              <div>{{ scope.row.remark || "--" }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="left">
            <template #default="scope">
              <div
                v-if="false"
                class="table-btn"
                :class="scope.row.status === 'PROCESSED' ? 'disabled' : ''"
                @click="scope.row.status === 'UNPROCESSED' && handle(scope.row)"
              >
                去处理
              </div>
              <div class="table-btn" @click="view(scope.row)">查看</div>
              <div
                v-if="userRole === 'admin'"
                class="table-btn"
                @click="deleteHandle(scope.row)"
              >
                删除
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1" class="pagination-wrapper">
      <el-pagination
        v-model="pagination.page"
        :total="pagination.totalElements"
        :page-size="pagination.size"
        background
        :hide-on-single-page="true"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <!-- 发布消息弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="addDialogVisible"
      title="发布消息"
      width="50%"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="消息内容" prop="name">
          <el-input
            v-model="addForm.description"
            placeholder="请输入消息内容"
            type="textarea"
            :rows="5"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="消息优先级" prop="priority">
          <el-select v-model="addForm.priority" placeholder="请选择消息优先级">
            <el-option label="紧急" value="URGENT" />
            <el-option label="提醒" value="REMINDER" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 处理消息弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="handleDialogVisible"
      title="处理消息"
      width="50%"
    >
      <div class="handle-message">
        您正在处理消息:{{ currentMessage.description }}
      </div>
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="处理结果" prop="status">
          <el-select v-model="handleForm.status" placeholder="请选择处理状态">
            <el-option label="已处理" value="PROCESSED" />
            <el-option label="未处理" value="UNPROCESSED" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理意见" prop="remark">
          <el-input
            v-model="handleForm.remark"
            placeholder="请输入处理意见"
            type="textarea"
            :rows="5"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitHandleForm"
            :loading="handleFormLoading"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 查看消息弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="viewDialogVisible"
      title="查看消息"
      width="50%"
    >
      <div class="handle-message">
        您正在查看的消息:{{ currentMessage.description }}
      </div>
      <div
        class="handle-priority"
        :class="currentMessage.priority === 'URGENT' ? 'abnormal' : 'normal'"
      >
        {{ currentMessage.priority === "URGENT" ? "紧急" : "提醒" }}
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatDate } from "@/assets/js/utils";
import { ListResponseType, PaginationType } from "@/api/globalType";
import {
  getMessagesAPI,
  addMessageAPI,
  processMessageAPI,
  deleteMessageAPI,
  AddMessageRequestType,
  SystemMessageType,
  ProcessMessageRequestType,
  MessageType,
  MessageScope,
  MessagePriority,
  MessageStatus,
} from "@/api/service/messages";

const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
let userRole = ref("user");
userInfo.roles.forEach((item: any) => {
  if (item.id === 1 || item.id === 2) {
    userRole.value = "admin";
  }
});

// 查询条件
const queryObj = ref({
  type: null,
  scope: null,
  priority: null,
  status: null,
});

// 分页
const pagination = ref<PaginationType>({
  page: 1,
  size: 50,
  totalElements: 0,
  totalPages: 0,
});

// 表格数据
const tableData = ref<SystemMessageType[]>([]);

// API调用保护状态
const listApiLoading = ref(false);

function getMessagesList() {
  // 防止并发调用
  if (listApiLoading.value) return;

  listApiLoading.value = true;

  getMessagesAPI({
    type: queryObj.value.type,
    scope: queryObj.value.scope,
    priority: queryObj.value.priority,
    status: queryObj.value.status,
    pageNum: pagination.value.page,
    pageSize: pagination.value.size,
  })
    .then((_data: any) => {
      const data = _data as ListResponseType<SystemMessageType>;
      tableData.value = data.content;
      pagination.value.page = data.page;
      pagination.value.size = data.size;
      pagination.value.totalElements = data.totalElements;
      pagination.value.totalPages = data.totalPages;
    })
    .catch(() => {
      ElMessage.error("获取消息列表失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getMessagesList();

// 筛选
function searchHandle() {
  pagination.value.page = 1;
  getMessagesList();
}

// 分页大小变化
function sizeChangeHandle(size: number) {
  pagination.value.size = size;
  pagination.value.page = 1;
  getMessagesList();
}
// 分页当前页变化
function currentChangeHandle(currentPage: number) {
  pagination.value.page = currentPage;
  getMessagesList();
}

// 发布消息
const addDialogVisible = ref(false);
const addFormLoading = ref(false);
const addForm = ref<AddMessageRequestType>({
  description: "",
  type: MessageType.SYSTEM_NOTIFICATION,
  scope: MessageScope.PLATFORM_WIDE,
  priority: MessagePriority.REMINDER,
});
const addFormRules = {
  description: [{ required: true, message: "请输入消息内容", trigger: "blur" }],
};
function addHandle() {
  addDialogVisible.value = true;
}
function resetAddForm() {
  addForm.value = {
    description: "",
    type: MessageType.SYSTEM_NOTIFICATION,
    scope: MessageScope.PLATFORM_WIDE,
    priority: MessagePriority.REMINDER,
  };
}

function submitAddForm() {
  if (addFormLoading.value) return;
  addFormLoading.value = true;
  addMessageAPI(addForm.value)
    .then(() => {
      ElMessage.success("发布消息成功");
      addDialogVisible.value = false;
      resetAddForm();
      getMessagesList();
    })
    .catch(() => {
      ElMessage.error("发布消息失败");
    })
    .finally(() => {
      addFormLoading.value = false;
    });
}

// 处理消息
const currentMessage = ref<SystemMessageType>({
  id: "",
  type: null,
  scope: null,
  description: "",
  priority: null,
  status: null,
  createdAt: null,
});
const handleDialogVisible = ref(false);
const handleFormLoading = ref(false);
const handleForm = ref<ProcessMessageRequestType>({
  id: "",
  status: MessageStatus.PROCESSED,
  remark: "",
});

function handle(row: SystemMessageType) {
  handleDialogVisible.value = true;
  currentMessage.value = row;
  handleForm.value = {
    id: row.id,
    status: MessageStatus.PROCESSED,
    remark: "",
  };
}
function submitHandleForm() {
  if (handleFormLoading.value) return;
  handleFormLoading.value = true;
  processMessageAPI(handleForm.value)
    .then(() => {
      ElMessage.success("处理消息成功");
      handleDialogVisible.value = false;
    })
    .catch(() => {
      ElMessage.error("处理消息失败");
    })
    .finally(() => {
      handleFormLoading.value = false;
    });
}

// 查看消息
const viewDialogVisible = ref(false);
function view(row: SystemMessageType) {
  viewDialogVisible.value = true;
  currentMessage.value = row;
}

// 删除消息
function deleteHandle(row: any) {
  const id = row.id;
  ElMessageBox.confirm("确定删除该消息吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteMessageAPI(id)
      .then(() => {
        ElMessage.success("删除消息成功");
        getMessagesList();
      })
      .catch(() => {
        ElMessage.error("删除消息失败");
      });
  });
}
</script>

<style scoped lang="scss">
#SystemNotifyPage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 1rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  flex-shrink: 0;
  padding: 1.5rem;
  background-color: #fff;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    padding-top: 1rem;
    padding-left: 1rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    padding-right: 2rem;
    .item-label {
      display: inline;
      padding-right: 1rem;
      flex-wrap: nowrap;
      text-align: right;
      color: $text-color-regular;
    }
    .item-input {
      width: 20rem;
    }
  }
  .search-btn {
    display: flex;
    align-items: center;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
  .add-btn {
    position: absolute;
    right: 12px;
    top: 1rem;
    display: flex;
    align-items: center;
    padding: 0.5rem 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    margin-top: 1rem;
    padding-left: 1rem;
    flex: 1;
    min-height: 0;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .table-btn.disabled {
    cursor: not-allowed;
    opacity: 0.5;
  }
  .signal-status.normal {
    color: $color_success;
  }
  .signal-status.abnormal {
    color: $color_danger;
  }
}

// 分页区域样式
.pagination-wrapper {
  flex-shrink: 0;
}

// 审批进度样式
.audit-progress-container {
  .progress-steps {
    .progress-step {
      display: flex;
      align-items: flex-start;
      position: relative;
      padding-bottom: 2rem;

      &:last-child {
        padding-bottom: 0;
      }

      .step-indicator {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 1rem;
        padding-top: 0.6rem;

        .step-circle {
          width: 1rem;
          height: 1rem;
          border-radius: 50%;
          border: 2px solid $border-color-primary;
          background-color: #fff;
          z-index: 2;
        }

        .step-line {
          position: absolute;
          top: 0.6rem;
          bottom: 0;
          width: 1px;
          background-color: $border-color-primary;
        }
      }

      .step-content {
        flex: 1;
        padding-top: 0.125rem;

        .step-title {
          font-size: $font-size-base;
          font-weight: 500;
          color: $text-color-regular;
          margin-bottom: 0.25rem;
        }
        .step-time {
          font-size: $font-size-tips;
          color: $text-color-secondary;
          margin-bottom: 0.25rem;
        }

        .step-handler {
          font-size: $font-size-tips;
          color: $text-color-secondary;
        }
      }

      // 已完成状态
      &.step-completed {
        .step-indicator {
          .step-circle {
            background-color: #52c41a;
            border-color: #52c41a;
          }
          .step-line {
            background-color: #52c41a;
          }
        }
        .step-content .step-title {
          color: #52c41a;
        }
      }

      // 进行中状态
      &.step-processing {
        .step-indicator {
          .step-circle {
            background-color: #1890ff;
            border-color: #1890ff;
          }
          .step-line {
            background-color: #d9d9d9;
          }
        }
        .step-content .step-title {
          color: #1890ff;
        }
      }

      // 待处理状态
      &.step-pending {
        .step-indicator {
          .step-circle {
            background-color: #fff;
            border-color: #d9d9d9;
          }
          .step-line {
            background-color: #d9d9d9;
          }
        }
        .step-content .step-title {
          color: #999;
        }
      }
    }
  }
}
.handle-message {
  margin-bottom: 2rem;
  padding-left: 3rem;
  font-size: $font-size-page-menu;
  color: $color_brand;
}
.handle-priority {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 2rem;
  margin-left: 3rem;
  padding-left: 3rem;
  height: 6rem;
  font-size: $font-size-page-menu;
  color: #fff;
  border-radius: 0.8rem;
}
.handle-priority.normal {
  background-color: rgba($color_success, 0.5);
}
.handle-priority.abnormal {
  background-color: rgba($color_danger, 0.5);
}
</style>
